package com.xexun.gpstracker.baby.mytree;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.nfc.Tag;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.msg.view.InputDialog;
import com.xexun.gpstracker.util.HttpUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by Administrator on 2016/11/23.
 */
public class WarningListAdapter extends BaseAdapter  implements View.OnClickListener {

    private String TAG = WarningListAdapter.class.getSimpleName();

    protected Context mContext;

    /**
     * 存储所有的Node
     */
    protected ArrayList<Warning> warningList;


    protected LayoutInflater mInflater;


    private int index;




    public WarningListAdapter(Context context, List<Warning> list) throws IllegalArgumentException,
            IllegalAccessException
    {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        warningList = new ArrayList<>(list);
    }




    @Override
    public int getCount() {
        return warningList.size();
    }

    @Override
    public Object getItem(int position) {
        return warningList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }




    //在外面先定义，ViewHolder静态类
    static class ViewHolder
    {

        public TextView content_text;
        public TextView time_text;
        public Button   editBtn;
    }


    public static String timedate(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        @SuppressWarnings("unused")
        long lcc = Long.valueOf(time);
        String times = sdr.format(new Date(lcc));
        return times;

    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView == null)
        {
            convertView = mInflater.inflate(R.layout.warninglist_item, parent, false);
            holder = new ViewHolder();
            holder.content_text = (TextView) convertView
                    .findViewById(R.id.content_text);
            holder.time_text = (TextView) convertView
                    .findViewById(R.id.time_text);
            holder.editBtn = (Button) convertView.findViewById(R.id.editBtn);
            holder.editBtn.setOnClickListener(this);
            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }

            Warning warning = warningList.get(position);

            holder.editBtn.setTag(position);
            holder.content_text.setText(warning.getContent());
            holder.time_text.setText(timedate(warning.getTime()));
            holder.editBtn.setText("处理");
            if (warning.getState() == 1){
                holder.editBtn.setText("已处理");
                convertView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        ViewHolder holder = (ViewHolder) v.getTag();

                        index = (int)holder.editBtn.getTag();
//                        LogUtil.i(TAG, "Index="+index);
                        deleteDialog();
                        return false;
                    }
                });
            }


        return convertView;
    }

    private void deleteDialog() {


        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

//                warningList.remove(index);
//                notifyDataSetChanged();
                Warning warning = warningList.get(index);
                removeGpsAlarm(warning.getId());



            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }



    static final String REMOVEAlARMURL = Constants.baseUrl+"position/removeGpsAlarm";
    private void removeGpsAlarm(String alarmID){
        JSONObject jsonObj = new JSONObject();


        try {
            jsonObj.put("id",alarmID) ;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        HttpUtil.post(REMOVEAlARMURL, jsonObj, new Callback.ProgressCallback<JSONObject>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

            }

            @Override
            public void onSuccess(JSONObject result) {
                warningList.remove(index);
                notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private InputDialog dialog;

    static final String DEALAlARMURL = Constants.baseUrl+"terminal/dealAlarm";

    @Override
    public void onClick(View v) {



        final Warning warning = warningList.get((int)v.getTag());

        if (warning.getState()==1){
            return;
        }

        dialog = new InputDialog((Activity) mContext, R.style.dialog, new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                JSONObject jsonObj = new JSONObject();


                try {
                    jsonObj.put("mongoAlarmId",warning.getId()) ;
                    jsonObj.put("remark",dialog.text_input.getText());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                HttpUtil.post(DEALAlARMURL, jsonObj, new Callback.ProgressCallback<JSONObject>() {
                    @Override
                    public void onWaiting() {

                    }

                    @Override
                    public void onStarted() {

                    }

                    @Override
                    public void onLoading(long total, long current, boolean isDownloading) {

                    }

                    @Override
                    public void onSuccess(JSONObject result) {

                        dialog.dismiss();
                        warning.setState(1);
                        notifyDataSetChanged();

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            }
        },mContext.getString(R.string.edit1));




        if(!dialog.isShowing()){
            dialog.show();
        }
//        Toast.makeText(mContext,"点击:" + (int)v.getTag(),Toast.LENGTH_SHORT).show();
    }







}
